import {
  Button,
  DatePicker,
  Empty,
  Input,
  Select,
  Table,
  TableProps,
  Card,
  Space,
  Typography,
  List,
} from 'antd'
import TableFilter, { FilterItemConfig } from '../components/TableFilter'
import React, { useEffect, useState } from 'react'
import { observer } from 'mobx-react'
import { usePagination } from 'alova/client'
import { UserOpenAccountPageVO } from '../api/globals'
import { formatDate } from '../uitls/common'
import { useNavigate } from 'react-router-dom'
import { dictsStore } from '../stores'
const { RangePicker } = DatePicker
const { Title, Text } = Typography

const OrderList = observer(() => {
  const [filterParams, setFilterParams] = useState<
    Record<string, string | number | [string, string] | undefined>
  >({})
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [selectedRows, setSelectedRows] = useState<UserOpenAccountPageVO[]>([])
  const [isMobile, setIsMobile] = useState(false)

  const navigate = useNavigate()

  useEffect(() => {
    const checkIfMobile = () => {
      setIsMobile(window.innerWidth <= 768)
    }

    // Initial check
    checkIfMobile()

    // Add event listener for window resize
    window.addEventListener('resize', checkIfMobile)

    // Cleanup
    return () => window.removeEventListener('resize', checkIfMobile)
  }, [])

  const filters: FilterItemConfig[] = [
    {
      key: 'name',
      label: '用户姓名',
      type: 'input',
      placeholder: '请输入用户姓名',
      component: <Input placeholder="请输入用户姓名" allowClear />,
    },
    {
      key: 'phone',
      label: '手机号码',
      type: 'input',
      placeholder: '请输入手机号码',
      component: <Input placeholder="请输入手机号码" allowClear />,
    },
    {
      key: 'status',
      label: '订单状态',
      type: 'select',
      placeholder: '请选择订单状态',
      component: (
        <Select
          placeholder="请选择"
          allowClear
          style={{ width: '100%' }}
          options={[
            { label: '待审核', value: 0 },
            { label: '已审核', value: 1 },
            { label: '已完成', value: 2 },
            { label: '已取消', value: 3 },
          ]}
        />
      ),
    },
    {
      key: 'createdTime',
      label: '下单时间',
      type: 'dateRange',
      span: 16,
      component: <RangePicker style={{ width: '100%' }} />,
    },
    {
      key: 'address',
      label: '用户地址',
      type: 'input',
      component: <Input placeholder="请输入用户地址" allowClear />,
    },
  ]

  // 处理搜索
  const handleSearch = (values: Record<string, unknown>) => {
    console.log('搜索参数:', values)
    setFilterParams(
      values as Record<string, string | number | [string, string] | undefined>
    )
  }

  // 处理重置
  const handleReset = () => {
    console.log('重置过滤器')
    setFilterParams({})
  }

  const MobileOrderCard = ({ record }: { record: UserOpenAccountPageVO }) => {
    const label = dictsStore.getDictKey('serviceStatus', record.status!)
    const color = dictsStore.getDictColor('serviceStatus', record.status!)

    const getActionButton = () => {
      if (record.status === 1) {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => navigate(`/detail/${record.id}?act=audit`)}
          >
            审核
          </Button>
        )
      }
      if (record.status === 2) {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => navigate(`/detail/${record.id}?act=csv`)}
          >
            创建勘探
          </Button>
        )
      }
      if (record.status === 4) {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => navigate(`/detail/${record.id}?act=rsv`)}
          >
            勘察结果
          </Button>
        )
      }
      if (record.status === 5) {
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => navigate(`/detail/${record.id}?act=rins`)}
          >
            安装结果
          </Button>
        )
      }
      return (
        <Button
          type="primary"
          size="small"
          onClick={() => navigate(`/detail/${record.id}`)}
        >
          详情
        </Button>
      )
    }

    return (
      <Card size="small" className="mb-3" actions={[getActionButton()]}>
        <div className="flex justify-between mb-2">
          <Text strong>{record.name}</Text>
          <Text style={{ color }}>{label}</Text>
        </div>
        <div className="mb-1">
          <Text type="secondary">手机: </Text>
          <Text>{record.phone}</Text>
        </div>
        <div className="mb-1">
          <Text type="secondary">产品: </Text>
          <Text>{record.productName}</Text>
        </div>
        <div>
          <Text type="secondary">时间: </Text>
          <Text>
            {record.createdTime ? formatDate(record.createdTime) : '-'}
          </Text>
        </div>
      </Card>
    )
  }

  const columns: TableProps<UserOpenAccountPageVO>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_, __, index) => index + 1,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '用户身份证号',
      dataIndex: 'idcard',
      key: 'idcard',
    },
    {
      title: '用户地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        const label = dictsStore.getDictKey('serviceStatus', record.status!)
        const color = dictsStore.getDictColor('serviceStatus', record.status!)
        return <span style={{ color }}>{label}</span>
      },
    },
    {
      title: '下单时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: (_, record) => {
        return record.createdTime ? formatDate(record.createdTime) : ''
      },
    },
    {
      title: '产品id',
      dataIndex: 'productId',
      key: 'productId',
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => {
        if (record.status === 1) {
          return (
            <Button
              type="primary"
              size="small"
              onClick={() => {
                navigate(`/detail/${record.id}?act=audit`)
              }}
            >
              审核
            </Button>
          )
        }
        if (record.status === 2) {
          return (
            <Button
              type="primary"
              size="small"
              onClick={() => {
                navigate(`/detail/${record.id}?act=csv`)
              }}
            >
              创建勘探任务
            </Button>
          )
        }
        if (record.status === 4) {
          return (
            <Button
              type="primary"
              size="small"
              onClick={() => {
                navigate(`/detail/${record.id}?act=rsv`)
              }}
            >
              录入勘察结果
            </Button>
          )
        }
        if (record.status === 5) {
          return (
            <Button
              type="primary"
              size="small"
              onClick={() => {
                navigate(`/detail/${record.id}?act=rins`)
              }}
            >
              录入安装结果
            </Button>
          )
        }
        return (
          <Button
            type="primary"
            size="small"
            onClick={() => {
              navigate(`/detail/${record.id}`)
            }}
          >
            查看详情
          </Button>
        )
      },
    },
  ]

  const rowSelection: TableProps<UserOpenAccountPageVO>['rowSelection'] = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows
      )
      setSelectedRowKeys(selectedRowKeys)
      setSelectedRows(selectedRows)
    },
  }

  const {
    data: orderList,
    loading,
    error,
    page,
    pageSize,
    total,
    update,
    refresh,
  } = usePagination(
    (page, pageSize) => {
      let pureFilterParams: Record<
        string,
        string | number | [string, string] | undefined
      > = {}
      if (filterParams) {
        pureFilterParams = Object.fromEntries(
          Object.entries(filterParams).filter(
            ([, value]) => value !== undefined && value !== null
          ) as [string, string | number | [string, string] | undefined][]
        )
      }
      return Apis.apply.Page({
        params: {
          pageNum: page,
          pageSize: pageSize,
          ...pureFilterParams,
        },
      })
    },
    {
      immediate: true,
      data: (response) => response.records,
      total: (response) => response.total,
      watchingStates: [filterParams],
    }
  )

  return (
    <div className="h-full flex flex-col">
      <Card variant="borderless" className="mb-4">
        <div className="flex justify-between items-center mb-4">
          <Title level={4} className="!mb-0">
            郑水净界·用户报装列表
          </Title>
          <Button
            type="primary"
            className="!bg-success"
            onClick={() => navigate('/oadd')}
          >
            新建申请单
          </Button>
        </div>

        <TableFilter
          filters={filters}
          onSearch={handleSearch}
          onReset={handleReset}
          initialValues={{ status: 0 }}
          showDivider={false}
        />
      </Card>

      <Card variant="borderless" className="flex-1">
        {error ? (
          <div className="w-full flex justify-center items-center py-8">
            <Empty
              description={
                <Space direction="vertical" align="center">
                  <span className="text-red-500 font-medium">
                    {(error as unknown as { msg: string }).msg}
                  </span>
                  <Button type="primary" onClick={() => refresh()}>
                    刷新
                  </Button>
                </Space>
              }
            />
          </div>
        ) : isMobile ? (
          <List
            dataSource={orderList}
            renderItem={(record) => <MobileOrderCard record={record} />}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              onChange: (page, pageSize) => update({ page, pageSize }),
              size: 'small',
              simple: true,
              showSizeChanger: false,
            }}
          />
        ) : (
          <Table
            rowKey="id"
            columns={columns}
            dataSource={orderList}
            loading={loading}
            rowSelection={rowSelection}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              onChange: (page, pageSize) => update({ page, pageSize }),
            }}
            scroll={{ x: 1200, y: 600 }}
          />
        )}
      </Card>
    </div>
  )
})
export default OrderList
